package com.l.controller;


import com.l.service.ConsumerService;
import com.l.service.ProducerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.TextMessage;

@Controller
public class MessageController {
    private Logger logger = LoggerFactory.getLogger(MessageController.class);
    @Resource(name = "demoQueueDestination")
    private Destination destination;

    //队列消息生产者
    @Resource(name = "producerService")
    private ProducerService producer;

    //队列消息消费者
    @Resource(name = "consumerService")
    private ConsumerService consumer;

    @RequestMapping(value = "/SendMessage", method = RequestMethod.POST)
    @ResponseBody
    public void send(String msg) {
        logger.info(Thread.currentThread().getName() + "------------send to jms Start");
        producer.sendMessage(msg);
        logger.info(Thread.currentThread().getName() + "------------send to jms End");
    }

    @RequestMapping(value = "/SendMessageTo", method = RequestMethod.POST)
    @ResponseBody
    public void sendTo(Destination destination, String msg) {
        logger.info(Thread.currentThread().getName() + destination.toString() + "------------send to jms Start");
        producer.sendMessage(msg);
        logger.info(Thread.currentThread().getName() + "------------send to jms End");
    }

    //@RequestMapping(value = "/ReceiveMessage", method = RequestMethod.GET, produces = "text/html; charset=UTF-8")
    @RequestMapping(value = "/ReceiveMessage", method = RequestMethod.GET)
    @ResponseBody
    public Object receive() {
        String msg = "";
        logger.info(Thread.currentThread().getName() + "------------receive from jms Start");
        TextMessage tm = consumer.receive(destination);
        logger.info(Thread.currentThread().getName() + "------------receive from jms End");
        try {
            if (tm != null) {
                msg = tm.getText();
            } else {
                msg = "消息队列中没有数据";
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
        return msg;
    }

}